package com.hgyc.mom.wms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hgyc.mom.common.util.StringUtils;
import com.hgyc.mom.core.mybatis.QueryWrapperUtil;
import com.hgyc.mom.wms.entity.WmsWarehouseUser;
import com.hgyc.mom.wms.mapper.WmsWarehouseUserMapper;
import com.hgyc.mom.wms.service.WmsWarehouseUserService;
import com.hgyc.mom.wms.vo.WmsWarehouseParam;
import com.hgyc.mom.wms.vo.WmsWarehouseVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.hgyc.mom.wms.mapper.WmsWarehouseMapper;
import com.hgyc.mom.wms.entity.WmsWarehouse;
import com.hgyc.mom.wms.service.WmsWarehouseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;
import com.hgyc.mom.common.exception.BizException;
import org.springframework.util.CollectionUtils;

/**
 * 仓库Service业务层实现
 *
 * @author fwj
 * @since 2025-05-14
*/
@Slf4j
@Service
public class WmsWarehouseServiceImpl extends ServiceImpl<WmsWarehouseMapper, WmsWarehouse> implements WmsWarehouseService {

    @Autowired
    private WmsWarehouseUserService wmsWarehouseUserService;

    @Override
    public List<WmsWarehouse> treeList(WmsWarehouseParam wmsWarehouseParam) {
        WmsWarehouse wmsWarehouse = new WmsWarehouse();
        BeanUtils.copyProperties(wmsWarehouseParam, wmsWarehouse);
        QueryWrapper<WmsWarehouse> wrapper = QueryWrapperUtil.build(wmsWarehouse);
        List<WmsWarehouse> list = list(wrapper);
        return this.convertToTree(list);
    }

    @Override
    public WmsWarehouse getByCode(String code) {
        LambdaQueryWrapper<WmsWarehouse> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmsWarehouse::getCode, code);
        return getOne(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveWarehouse(WmsWarehouseVO wmsWarehouseVO) {
        WmsWarehouse wmsWarehouse = new WmsWarehouse();
        BeanUtils.copyProperties(wmsWarehouseVO, wmsWarehouse);

        String code = wmsWarehouse.getCode();
        if (StringUtils.isEmpty(code)) {
            throw new BizException("编码不能为空");
        }
        WmsWarehouse existWm = this.getByCode(code);
        if (existWm != null) {
            throw new BizException("编码" + code + "已存在");
        }

        if (wmsWarehouse.getParentId() == null) {
            wmsWarehouse.setParentId(0L);
        }

        save(wmsWarehouse);

        //新增子表
        List<Long> insertUserIds = wmsWarehouseVO.getInsertUserIds();
        if (!CollectionUtils.isEmpty(insertUserIds)) {
            List<WmsWarehouseUser> users = new ArrayList<>();
            for (Long userId : insertUserIds) {
                WmsWarehouseUser wmsWarehouseUser = new WmsWarehouseUser();
                wmsWarehouseUser.setUserId(userId);
                wmsWarehouseUser.setWarehouseId(wmsWarehouse.getId());
                users.add(wmsWarehouseUser);
            }
            if (!CollectionUtils.isEmpty(users)) {
                wmsWarehouseUserService.saveBatch(users);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateWarehouse(WmsWarehouseVO wmsWarehouseVO) {
        WmsWarehouse wmsWarehouse = new WmsWarehouse();
        BeanUtils.copyProperties(wmsWarehouseVO, wmsWarehouse);

        updateById(wmsWarehouse);

        //新增子表
        List<Long> insertUserIds = wmsWarehouseVO.getInsertUserIds();
        if (!CollectionUtils.isEmpty(insertUserIds)) {
            List<WmsWarehouseUser> users = new ArrayList<>();
            for (Long userId : insertUserIds) {
                WmsWarehouseUser wmsWarehouseUser = new WmsWarehouseUser();
                wmsWarehouseUser.setUserId(userId);
                wmsWarehouseUser.setWarehouseId(wmsWarehouse.getId());
                users.add(wmsWarehouseUser);
            }
            if (!CollectionUtils.isEmpty(users)) {
                wmsWarehouseUserService.saveBatch(users);
            }
        }

        //删除子表
        List<Long> deleteUserIds = wmsWarehouseVO.getDeleteUserIds();
        if (!CollectionUtils.isEmpty(deleteUserIds)) {
            LambdaQueryWrapper<WmsWarehouseUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.in(WmsWarehouseUser::getUserId, deleteUserIds);
            wrapper.eq(WmsWarehouseUser::getWarehouseId, wmsWarehouse.getId());
            wmsWarehouseUserService.remove(wrapper);
        }
    }

    /**
    * {@inheritDoc}
    */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importData(List<WmsWarehouse> wmsWarehouseList, boolean updateSupport) {
        if (wmsWarehouseList == null || wmsWarehouseList.isEmpty()) {
            throw new IllegalArgumentException("导入数据不能为空");
        }

        try {
            if (updateSupport) {
                // TODO 实现更新已有数据的导入逻辑
                return "更新导入成功，共导入 " + wmsWarehouseList.size() + " 条数据";
            } else {
                // TODO 实现不更新已有数据的导入逻辑
                return "新增导入成功，共导入 " + wmsWarehouseList.size() + " 条数据";
            }
        } catch (Exception e) {
            log.error("仓库导入失败", e);
            throw new BizException("仓库导入失败：" + e.getMessage());
        }
    }

    private List<WmsWarehouse> convertToTree(List<WmsWarehouse> wmsWarehouseList) {
        Map<Long, List<WmsWarehouse>> parentChildrenMap = new HashMap<>();
        for (WmsWarehouse wmsWarehouse : wmsWarehouseList) {
            Long parentId = wmsWarehouse.getParentId();

            // 将当前菜单项添加到父菜单项的子菜单项列表中
            List<WmsWarehouse> children = parentChildrenMap.getOrDefault(parentId, new ArrayList<>());
            children.add(wmsWarehouse);
            parentChildrenMap.put(parentId, children);

        }
        // 将根节点的子菜单项列表转换为树形结构
        List<WmsWarehouse> rootChildren = parentChildrenMap.getOrDefault(0L, new ArrayList<>());
        for (WmsWarehouse wmsWarehouse : rootChildren) {
            convertToTree(wmsWarehouse, parentChildrenMap);
        }
        return rootChildren;
    }

    private void convertToTree(WmsWarehouse parent, Map<Long, List<WmsWarehouse>> parentChildrenMap) {
        Long parentId = parent.getId();
        List<WmsWarehouse> children = parentChildrenMap.getOrDefault(parentId, new ArrayList<>());
        parent.setChildren(children);
        for (WmsWarehouse child : children) {
            convertToTree(child, parentChildrenMap);
        }
    }
}